<!-- 用户登录界面 -->
<!-- 它应该被包含在Setting组件中 -->
<!-- 作用就是：登录/登出 -->
<template>
  
  <!-- 登录 -->
  <div class="login-container" v-show="showLogin">
    <div class="login">
      <div class="login_caption">
        <h2>登录</h2>
      </div>
      <form @submit.prevent="login">
        <div>
          <label for="username">用户名：</label>
          <input type="text" id="username" v-model="username" required>
        </div>
        <div>
          <label for="password">密码：</label>
          <input type="password" id="password" v-model="password" required>
        </div>
        <button type="submit">登录</button>
      </form>
      <div id="enroll">
        <label for="">还没账号？</label>
        <button type="button" @click="register">注册</button>
      </div>

    </div>
  </div>

  <!-- 账户信息 -->
  <div class="account-container" v-show="showUserInfo">
    <div class="account">
      <img alt="PandSo" src="../assets/img/setting.svg" />
      <span>{{ user.username }}</span>
    </div>
    <div class="xiangqing">
      <div>
        <li>用户名: {{ user.username }}</li>
      </div>
      <div>
        <li @click="openChangePasswordModal()">密码: <span v-if="!showPassword">{{ hidePassword(user.userpassword)
        }}</span><span v-else>{{ user.userpassword
}}</span> <button @click.stop="togglePasswordVisibility">{{ showPassword ? '隐藏密码' : '显示密码' }}</button></li>
      </div>
      <div>
        <li>邮箱: {{ user.usermail }}</li>
      </div>
      <div><button @click="logout">退出账户</button></div>
    </div>
  </div>



  <!-- 修改密码弹窗 -->
  <div class="modal-container" v-show="showChangePasswordModal">
    <div class="modal">
      <h2>修改密码</h2>
      <form @submit.prevent="changePassword">
        <div>
          <label for="current-password">当前密码：</label>
          <input type="password" id="current-password" v-model="currentPassword" required>
        </div>
        <div>
          <label for="new-password">新密码：</label>
          <input type="password" id="new-password" v-model="newPassword" required>
        </div>
        <button type="submit">确认修改</button>
        <button type="button" @click="cancelChangePassword">取消</button>
      </form>
    </div>
  </div>

  <!-- 注册 -->
  <div class="login-container" v-show="showEnroll">
    <div class="login">
      <h2>注册</h2>
      <form @submit.prevent="register">
        <div>
          <label for="username">用户名：</label>
          <input type="text" id="username" v-model="username" required>
        </div>
        <div>
          <label for="password">密码：</label>
          <input type="password" id="password" v-model="password" required>
        </div>
        <div>
          <label for="email">邮箱：</label>
          <input type="text" id="email" v-model="email" required>
        </div>
        <button type="submit" @click="userregister">注册</button>
        <button type="button" @click="quit">退出</button>
      </form>
    </div>
  </div>
</template>
  
<script setup lang="ts">

import { ref, onMounted } from 'vue'
import { userlogin, userenroll, updataUserPassword,LoginTime } from '../api/post';
import { checkUserLogin, storage } from '../utils';
import { getUserInfo } from '../api/get';
import { getCurrentInstance } from 'vue'
//@ts-ignore
import { ElMessage } from 'element-plus'

// 在你的 setup 方法中
const { appContext } = getCurrentInstance()!


const showPassword = ref(false);
const username = ref('')
const password = ref('')
const email = ref('')
const showLogin = ref(true)
const showEnroll = ref(false)
const showUserInfo = ref(false)
const showChangePasswordModal = ref(false);
const currentPassword = ref('');
const newPassword = ref('');
const loginTime = ref('')



// 打开修改密码弹窗
const openChangePasswordModal = () => {
  showChangePasswordModal.value = true;
};

// 取消修改密码
const cancelChangePassword = () => {
  showChangePasswordModal.value = false;
  currentPassword.value = '';
  newPassword.value = '';
};

// 提交修改密码
const changePassword = () => {
  // 在此处处理修改密码的逻辑
  if(currentPassword.value === user.value.userpassword){
    const res = updataUserPassword(newPassword.value);
    res.then(res=>{
      alert(res.data)
      window.location.reload();
    })
  }else{
    ElMessage.error({
      message: '当前密码错误',
      type: 'fail',
       // 将 appContext 作为选项传递给 ElMessage
    },appContext)
  }
  
  showChangePasswordModal.value = false;
  currentPassword.value = '';
  newPassword.value = '';
};
const user = ref<{
  username: string,
  userpassword: string,
  usermail: string
  userId: number
}>({
  username: '',
  userpassword: '',
  usermail: '',
  userId: 0
})
// import {user} from "../api/user"


function login() {
  // 在这里处理登录逻辑
  userlogin(username.value, password.value).then(res => {
    if (res == "500") {
      alert("服务器错误")
    } else if (res == "415") {
      alert("账号或密码错误")
    } else {
      showLogin.value = !showLogin.value
      showUserInfo.value = !showUserInfo.value
      storage.set("token", res)
      alert("登录成功")
      loginTime.value = new Date().toISOString(); // 获取当前时间并转换为ISO格式字符串
      LoginTime(loginTime.value).then(res =>{
        console.log(res);
         window.location.reload();
      }) 
    }
  })
}

// 这里是组件加载时的操作：
//  判断是否本地存储token（登录状态）
//      如果有，则默认已登陆，并且向后端发起请求：“请求获得用户信息（邮箱，账号，密码）”
//                          获得状态码：200（成功->展示用户信息）404（失败->重新登录）
//      如果没有，则不操作（false->登录页面）
onMounted(() => {
  showLogin.value = !checkUserLogin()
  if (!showLogin.value) {
    getUserInfo().then(res => {
      if (res == "404") {
        alert("该用户不存在,请重新登录")
        storage.set("token", '')
        // 此时 showlogin:false->true showEnroll:false showUserInfo:false
        showLogin.value = !showLogin.value
      } else if (res == "401") {
        alert("用户登录已经过期，请重新登录")
        storage.set("token", '')
        // 此时 showlogin:false->true showEnroll:false showUserInfo:false
        showLogin.value = !showLogin.value
      } else {
        // 此时 showlogin:false showEnroll:false showUserInfo:false->true
        showUserInfo.value = !showUserInfo.value
        user.value = res
      }
    })
  }
}
)
function logout() {
  // 在这里处理退出逻辑
  storage.set("token", '')
  showLogin.value = !showLogin.value
  showUserInfo.value = !showUserInfo.value
}
function register() {
  // 进入注册界面
  showLogin.value = !showLogin.value
  showEnroll.value = !showEnroll.value
}

function userregister() {
  //用户注册
  userenroll(username.value, password.value, email.value).then(res => {
    if (res == "409") {
      alert("用户存在")
    } else if (res == '400') {
      alert("注册失败")
    } else if (res == '201') {
      alert("注册成功")
      showEnroll.value = !showEnroll.value
      showLogin.value = !showLogin.value
    }
  })
}
function quit() {
  //返回登录界面
  showEnroll.value = !showEnroll.value
  showLogin.value = !showLogin.value
}

function hidePassword(password: string): string {
  // 将密码转换为星号或其他隐藏形式
  return password.replace(/./g, "*");
}

function togglePasswordVisibility() {
  showPassword.value = !showPassword.value;
}

</script>
  
<style scoped>
@import '../style/user.css';

img {
  width: 24px;
  height: 24px;
}

.account-container {
  display: block;
  padding: 10px;
  background-color: #f5f5f5;
  backdrop-filter: blur(8px);
  /* 添加玻璃浮动效果 */
}

.account {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.account img {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.xiangqing div {
  margin-bottom: 10px;
}

.xiangqing li {
  list-style: none;
  font-size: 14px;
  line-height: 1.5;
}

.xiangqing li button {
  border: none;
  background-color: transparent;
  color: #007bff;
  cursor: pointer;
}

.modal-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal {
  width: 400px;
  padding: 20px;
  background-color: #fff;
}

.modal h2 {
  margin-top: 0;
}

.modal form div {
  margin-bottom: 10px;
}

.modal button {
  margin-right: 10px;
}
</style>

